//
//  UITableViewController+HDMyInformation.m
//  app
//
//  Created by D on 15/4/10.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDMyInformation.h"
#import "HDUserInforHttpRequestManger.h"
#import "HDLoginoutViewController.h"
#import "ParticipationDataManager.h"
#import "HZMallSqlDataManager.h"

@implementation HDMyInformation

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self freshUser];
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setSeparatorColor:[UIColor clearColor]];
    self.infoArray = [NSArray array];
 
    
}

-(void)freshUser
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]) {
       
        if (![[NSUserDefaults standardUserDefaults]boolForKey:@"got"]) {
            self.result_userinfo = [JKRemoteResult target:self action:@selector(getuserinfo:)];
            
            HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
            NSDictionary * params = @{};
            [httpManager getUserInfoWithParams:params result:self.result_userinfo];
        }else
        {
            [self loadUserData];
        }

        
    }else
    {
        [self loadUserData];
    }
    
    
}

-(void)getuserinfo:(JKRemoteResult*)rt
{
 
    if (rt.failure) {
        return;
    }
    NSLog(@"gender = %@",[[rt.content objectForKey:@"user_info"] objectForKey:@"gender"]);
    
    if ([[[rt.content objectForKey:@"user_info"] objectForKey:@"nlv_icon"] length] == 0) {
       
        [[NSUserDefaults standardUserDefaults] setObject:@"0"  forKey:@"nlv_icon"];
        
    }else
    {
       [[NSUserDefaults standardUserDefaults] setObject:[[rt.content objectForKey:@"user_info"] objectForKey:@"nlv_icon"] forKey:@"nlv_icon"];
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:[[rt.content objectForKey:@"user_info"] objectForKey:@"nickname"] forKey:@"nickname"];
    [[NSUserDefaults standardUserDefaults] setObject:[[rt.content objectForKey:@"user_info"] objectForKey:@"gender"] forKey:@"gender"];
    [[NSUserDefaults standardUserDefaults] setObject:[[rt.content objectForKey:@"user_info"] objectForKey:@"signature"] forKey:@"signature"];
    [[NSUserDefaults standardUserDefaults] setObject:[[rt.content objectForKey:@"user_info"] objectForKey:@"level_icon"] forKey:@"level_icon"];
    
    [[NSUserDefaults standardUserDefaults] setObject:[[rt.content objectForKey:@"user_info"] objectForKey:@"haveuniqueID"] forKey:@"haveuniqueID"];
    [[NSUserDefaults standardUserDefaults] setObject:[[rt.content objectForKey:@"user_info"] objectForKey:@"exp"] forKey:@"exp"];
    [[NSUserDefaults standardUserDefaults] setObject:[[rt.content objectForKey:@"user_info"] objectForKey:@"edit_gender"] forKey:@"edit_gender"];
    [[NSUserDefaults standardUserDefaults] setObject:[[rt.content objectForKey:@"user_info"] objectForKey:@"face"] forKey:@"face"];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"got"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
     [self loadUserData];
}

-(void)loadUserData
{
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]) {
        
       
        
        
        self.nicknameLab.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"nickname"];

        self.daRenHaoLab.text = @"达人号:";
        NSString* darenStr = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uniqueID"]];
        self.daRenhao.text = [NSString stringWithFormat:@"%@",[darenStr lowercaseString]];
        
        self.levelLab.text = [NSString stringWithFormat:@"LV%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"level"]];
        
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"headImage"]) {
           
            UIImage * image = [UIImage imageWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"headImage"]];
            [self.faceImg setImage:image];
            
        }else
        {
            if ([[SDImageCache sharedImageCache] imageFromDiskCacheForKey:@"userHead"]) {
                
                [self.faceImg setImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:@"userHead"]];
            }else
            {
                [self.faceImg sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"face"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    
                    NSData * data = UIImageJPEGRepresentation(image,1.0);
                    [[SDImageCache sharedImageCache] storeImage:image recalculateFromImage:YES imageData:data forKey:@"userHead" toDisk:YES];
                }];
            }
            
            

            
            
            
        }
    
        

        
        self.faceImg.layer.masksToBounds = YES;
        self.faceImg.layer.cornerRadius = UF(6); //UF(6)为圆角角度
        
        UIImage * BGimage = [UIImage imageNamed:@"color_gray@2x.png"];
        CGFloat top = 6;
        CGFloat bottom = 6;
        CGFloat left = 6;
        CGFloat right = 6;
        UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
        BGimage = [BGimage resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        
        UIImage * BGimage2 = [UIImage imageNamed:@"head_144.png"];
        UIEdgeInsets insets2 = UIEdgeInsetsMake(top, left, bottom, right);
        BGimage2 = [BGimage2 resizableImageWithCapInsets:insets2 resizingMode:UIImageResizingModeStretch];
        [self.lineImage setImage:BGimage2];
        
        [self.placeLogin_btn setBackgroundImage:BGimage forState:UIControlStateNormal];
        [self.placeLogin_btn setTitle:@"退出当前账户" forState:UIControlStateNormal];
        
    }else
    {
        
        [self.levelImg removeFromSuperview];
        [self.levelLab removeFromSuperview];
        [self.daRenHaoLab removeFromSuperview];
        [self.faceImg setImage:[UIImage imageNamed:@"visitor@2x.png"]];
        self.nicknameLab.text = @"账户未登录";
        UIImage * BGimage = [UIImage imageNamed:@"color@2x.png"];
        CGFloat top = 6;
        CGFloat bottom = 6;
        CGFloat left = 6;
        CGFloat right = 6;
        UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
        BGimage = [BGimage resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        [self.placeLogin_btn setBackgroundImage:BGimage forState:UIControlStateNormal];
    }
    
     self.result = [JKRemoteResult target:self action:@selector(checkVersion:)];
    self.result_logout = [JKRemoteResult target:self action:@selector(loginOut:)];
    
//    [self levelImage];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//   
//    
//}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]) {
        [[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:nil message:@"尚未登陆" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [self.view addSubview:av];
        [av show];
        
    }
    
    NSUInteger section=[indexPath section];

    switch (section) {
        case 0:
        {
            if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] > 0)
            {
                [[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleDefault];
                
                self.navigationController.toolbarHidden = YES;
                UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"MainStoryBoard" bundle:nil];
                self.moreView = [storyBoard instantiateViewControllerWithIdentifier:@"more"];
                
                [self.navigationController pushViewController:self.moreView animated:YES];
//                [self presentViewController:moreInfo animated:NO completion:nil];
            }
            
            
        }
            break;
        case 1:
        {
           
            if ([[NSUserDefaults standardUserDefaults]objectForKey:@"uid"])
            {
                
                [[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleDefault];
                
                if (indexPath.row == 0) {
                    
//                    MyCollectionViewController * myCollect = [[MyCollectionViewController alloc]init];
//                    myCollect.uid = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
//                    myCollect.hidesBottomBarWhenPushed = YES;
//                    [self.navigationController pushViewController:myCollect animated:YES];
                   
                    
                }else
                {
//                    MyForumViewController * myForm = [[MyForumViewController alloc]init];
//                    myForm.uid = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
//                    myForm.hidesBottomBarWhenPushed = YES;
//                    [self.navigationController pushViewController:myForm animated:YES];

                }

            }
            
        }
            break;
        case 2:
        {
       
            if ([[NSUserDefaults standardUserDefaults]objectForKey:@"uid"])
            {
//                [[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleDefault];
                
                //            版本检测
                self.progress_ = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:self.progress_];
                [self.view bringSubviewToFront:self.progress_];
                self.progress_.delegate = self;
                self.progress_.labelText = @" 版本检测中...";
                [self.progress_ show:YES];
                
                NSString *URL = @"http://itunes.apple.com/lookup?id=960909368";
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
                [request setURL:[NSURL URLWithString:URL]];
                [request setHTTPMethod:@"POST"];
                NSHTTPURLResponse *urlResponse = nil;
                NSError *error = nil;
                NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
                
                NSString *results = [[NSString alloc] initWithBytes:[recervedData bytes] length:[recervedData length] encoding:NSUTF8StringEncoding];
                NSDictionary *dic = [results JSONValue];
                self.infoArray = [dic objectForKey:@"results"];
                
                [self onCheckVersion];
                
//                HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
//                NSDictionary * params = @{@"channel":@"jiankang",
//                                          @"appver":APP_VERSION,
//                                          @"platform":@"ios"};
//                [httpManager checkVersionWithParams:params result:self.result];
            }
            

            
        }
            break;
        case 3:
        {
      
        }
        default:
            break;
    }
    
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - section 间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 16;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
#pragma mark - 跳转iTunes 检查版本
-(void)onCheckVersion
{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    //CFShow((__bridge CFTypeRef)(infoDic));
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
    

    if (self.progress_) {
        [self.progress_ removeFromSuperview];
        self.progress_ = nil;
    }
    
    if ([self.infoArray count]) {

        NSDictionary *releaseInfo = [self.infoArray objectAtIndex:0];
        NSString *lastVersion = [releaseInfo objectForKey:@"version"];

        if ([lastVersion isEqualToString:currentVersion]) {
            //trackViewURL = [releaseInfo objectForKey:@"trackVireUrl"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"此版本为最新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag = 10001;
            [alert show];
            
                    }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
            alert.tag = 10000;
            [alert show];

        }
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==10000) {
        if (buttonIndex==1) {
            NSURL *url = [NSURL URLWithString:@"itms-apps://itunes.apple.com/cn/app/id960909368?mt=8"];
            [[UIApplication sharedApplication]openURL:url];
        }
    }else
    {
        [alertView removeFromSuperview];
    }
}

#pragma mark - 游客请登录/退出账号
- (IBAction)placeLogin:(id)sender {
    
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]) {
        self.navigationController.toolbarHidden = YES;
        
        HDAppDelegate* app = (HDAppDelegate*)[[UIApplication sharedApplication]delegate];
        app.storyBoard = [UIStoryboard storyboardWithName:@"LogInOutStoryboard" bundle:nil];
    
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"visitor"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
//        [self.navigationController pushViewController:logview animated:YES];
//        [self presentViewController:[app.storyBoard instantiateInitialViewController] animated:NO completion:nil];
        
        UIViewController * loginOut = [app.storyBoard instantiateViewControllerWithIdentifier:@"login"];
        loginOut.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginOut animated:YES];
        
    }else
    {
        self.progress_ = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:self.progress_];
        [self.view bringSubviewToFront:self.progress_];
        self.progress_.delegate = self;
        self.progress_.labelText = @"正在退出中...";
        [self.progress_ show:YES];
        
        HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
        NSDictionary * params = @{@"version":APP_VERSION};
        [httpManager loginOutWithParams:params result:self.result_logout];
    }
    
    

}
#pragma mark - 退出账号
-(void)loginOut:(JKRemoteResult*)rt
{
    
    if (self.progress_) {
        [self.progress_ removeFromSuperview];
        self.progress_ = nil;
    }
    
    
 
    if (rt.failure) {
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:nil message:@"请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [self.view addSubview:av];
        [av show];
        
        return;
    }
    NSString * uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uid"];
    NSString * allInformation = [[NSBundle mainBundle] bundleIdentifier];
    [[NSUserDefaults standardUserDefaults]removePersistentDomainForName:allInformation];

    [[SDImageCache sharedImageCache]removeImageForKey:@"userHead"];
    [[SDImageCache sharedImageCache]removeImageForKey:@"userLevel_icon"];
    [[SDImageCache sharedImageCache]removeImageForKey:@"userNlv_icon"];
    
    /** 删除本地缓存信息 -write by khzliu */
    [[HZMallSqlDataManager defaultManager]  deleteAllProductChoseStatus];
    [[HZMallSqlDataManager defaultManager] deleteAllAddressCacheData];
    [[HZMallSqlDataManager defaultManager] deleteAllSearchHistoryCacheData];
    [[HZMallSqlDataManager defaultManager] deleteAllOfflineCartsCacheData];
    

    
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstLaunch"];
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"userLogout"];
    [[NSUserDefaults standardUserDefaults] setObject:uid forKey:@"mark"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    HDAppDelegate* app = (HDAppDelegate*)[[UIApplication sharedApplication]delegate];
    
    app.storyBoard = [UIStoryboard storyboardWithName:@"LogInOutStoryboard" bundle:nil];
    
    app.window.rootViewController = [app.storyBoard instantiateInitialViewController];
    [app.window makeKeyAndVisible];
    
//    [self presentViewController:[app.storyBoard instantiateInitialViewController] animated:NO completion:nil];
  
    
}
@end
